<template>
  <div class="cesium">
    <div id="cesium_container">
      <el-button @click="changeType(3)">切换到3D</el-button>
      <el-button @click="changeType(2)">切换到2.5D</el-button>
      <el-button @click="changeType(1)">切换到2D</el-button>
    </div>
  </div>
</template>

<script>
// import utils from '@/plugins/utils'
// import { GetConfigType } from '@/api/system.js'
import * as Cesium from "cesium";
import "../../public/Cesium/Widgets/widgets.css";
export default {
  name: "Cesium",
  data() {
    return {
      towerTileset: null,
      token: "",
      address: ["123.285555", "41.641111"], //沈阳测试航空站
      isLoadTerrain: false,
    };
  },
  mounted() {
    this.initCesium();
  },
  methods: {
    changeType(value) {
      let scene = window.viewer.scene;
      if (value === 3) {
        scene.morphTo3D(0);
      }else if(value===2){
        scene.morphToColumbusView(0)
      }else {
        scene.morphTo2D(0);
      }
    },
    async getToken() {
      let { data: res } = await GetConfigType({ type: "3D_MAP_VISITE_KEY" });
      if (res.code < 0) {
        this.$message.error(message.error);
        return false;
      }
      this.token = res.data.value
        ? res.data.value
        : "2b5c52e1d94f221834f1c2d616a63492";
    },

    async getIsEnableTerrain() {
      let { data: res } = await GetConfigType({ type: "IS_ENABLE_TERRAIN" });
      if (res.code < 0) {
        this.$message.error(message.error);
        return false;
      }
      this.isLoadTerrain = res.data.value === "true" ? true : false;
    },

    async initCesium(callBack = function () {}) {
      //  let token = 'fd63ef654ec13b0c5355c2dd57eca60c'; // 2b5c52e1d94f221834f1c2d616a63492   8096e1e5a85113ad261408361166bf2f   fd63ef654ec13b0c5355c2dd57eca60c

      // await this.getToken();
      // await this.getIsEnableTerrain();
      // 服务域名
      //   let subdomains = ["0", "1", "2", "3", "4", "5", "6", "7"];
      //   //add by zl
      //   let tdtUrl = "https://t{s}.tianditu.gov.cn/";
      //  let imgMap = new Cesium.UrlTemplateImageryProvider({
      //     url: tdtUrl + "DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + this.token,
      //     // url: 'http://http://192.168.30.254:9203' + '/tiles/{z}/{x}/{y}.jpg',
      //       fileExtension: "jpg" + this.token,
      //     subdomains: subdomains, // 服务负载子域
      //     tilingScheme: new Cesium.WebMercatorTilingScheme(),
      //     maximumLevel: 18,
      //   });

      // Cesium.Ion.defaultAccessToken =
      //   "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIzZGM1YjQwMi03NGIxLTQ5YWEtOThiOS00MzUzZTUyMWIwMDEiLCJpZCI6Mzc1MzgsImlhdCI6MTYwNTE3NTM3NH0.ryzQ3uf-JpPrpz71pgsdmdoq2IOxuj_miVPmWHP6ZRo";
      // 初始化cesium视图

      window.viewer = new Cesium.Viewer("cesium_container", {
        animation: false, //是否显示动画控件
        baseLayerPicker: false, //是否显示图层选择控件
        fullscreenButton: false, //全屏按钮
        selectionIndicator: false,
        shadows: false, //阴影
        scene3DOnly: true, //只显示3d模式
        shouldAnimate: false, //开启动画
        geocoder: false, //是否显示地名查找控件
        timeline: false, //是否显示时间线控件
        sceneModePicker: false, //是否显示投影方式控件
        navigationHelpButton: false, //是否显示帮助信息控件
        infoBox: false, //是否显示点击要素之后显示的信息
        homeButton: false, //主页控件
        // imageryProvider: imgMap,
        // terrainProvider: new Cesium.CesiumTerrainProvider({
        //   url: Cesium.IonResource.fromAssetId(1),
        // }),
        // imageryProvider: new Cesium.UrlTemplateImageryProvider({
        //   url: '/img/tiles/{z}/{x}/{y}.jpg',
        //   fileExtension: 'jpg'
        // })
      });
      // 蓝色星球
      // window.viewer.imageryLayers.get(0).show = true

      // 加载地形
      if (this.isLoadTerrain) {
        window.viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
          url: Cesium.IonResource.fromAssetId(1),
        });
      }

      // let tdWays = new Cesium.UrlTemplateImageryProvider({
      //   url: "/img/tiles/{z}/{x}/{y}.jpg",
      //   minimumLevel: 3,
      //   maximumLevel: 18,
      // });
      let tdWays = new Cesium.UrlTemplateImageryProvider({
        url: "file:///Users/xzh/Documents/workspace/Project/vue3Project/public/tiles/{z}/{x}/{y}.png",
        minimumLevel: 3,
        maximumLevel: 18,
      });
      window.viewer.imageryLayers.addImageryProvider(tdWays);

      //去锯齿
      viewer.scene.fxaa = true;
      viewer.scene.postProcessStages.fxaa.enabled = true;
      //去除注册显示信息
      viewer.cesiumWidget.creditContainer.style.display = "none";
      viewer.scene.globe.depthTestAgainstTerrain = true;
      //最大，最小缩放
      viewer.scene.screenSpaceCameraController.minimumZoomDistance = 20;
      viewer.scene.screenSpaceCameraController.maximumZoomDistance = 15000000;
      //左右键操作习惯更改
      viewer.scene.screenSpaceCameraController.tiltEventTypes = [
        Cesium.CameraEventType.RIGHT_DRAG,
        Cesium.CameraEventType.PINCH,
      ];
      viewer.scene.screenSpaceCameraController.zoomEventTypes = [
        Cesium.CameraEventType.MIDDLE_DRAG,
        Cesium.CameraEventType.WHEEL,
        Cesium.CameraEventType.PINCH,
      ];
      this.flyToPoint(+this.address[0], +this.address[1], 15000);

      callBack();

      // // 让地形的TileScheme设置成墨卡托投影
      // let ellipsoidProvider = new Cesium.EllipsoidTerrainProvider();
      //     viewer.terrainProvider = ellipsoidProvider;
    },

    // 飞行到具体某一点
    flyToPoint(longitude, latitude, height) {
      // longitude:经度 latitude:纬度 longitude:高度
      window.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(longitude, latitude, height),
        orientation: {
          heading: Cesium.Math.toRadians(0.0),
          pitch: Cesium.Math.toRadians(-90.0),
          roll: 0.0,
        },
      });
    },

    // 绘制航迹线路 点位 及编号
    track(data, points) {
      var boundPositions = []; /*绑定位置 数组 */
      data.labelCollection = window.viewer.scene.primitives.add(
        new Cesium.LabelCollection()
      );
      data.pointCollection = window.viewer.scene.primitives.add(
        new Cesium.PointPrimitiveCollection()
      );
      for (var i in points) {
        /*取经纬度 高度 和该航迹的id */
        var newPoint = {
          altitude: points[i].altitude * 1,
          id: points[i].id,
          lat: points[i].lat * 1,
          lng: points[i].lng * 1,
          traceId: data.id,
        };

        /*相机有行动 标点为青色 无 为橙色*/
        var color;
        if (points[i].cameraAction === 0) {
          color = new Cesium.Color.fromCssColorString("#f86127");
        } else {
          color = new Cesium.Color.fromCssColorString("#00e5f8");
        }

        /*定位 转换格式 */
        var position = Cesium.Cartesian3.fromDegrees(
          parseFloat(newPoint.lng),
          parseFloat(newPoint.lat),
          parseFloat(newPoint.altitude)
        );
        /*将转换的对象 放进绑定位置数组中 */
        boundPositions.push(position);

        /*标点 */
        data.pointCollection.add({
          show: true,
          position: position,
          color: color,
          pixelSize: 10,
        });

        /*数字编号 */
        data.labelCollection.add({
          position: position,
          text: (i * 1 + 1).toString(),
          font: "18px Arial",
          fillColor: color,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          // disableDepthTestDistance : Number.POSITIVE_INFINITY,
        });
        data.points[i].newPoint = JSON.parse(JSON.stringify(newPoint));
      }
      if (boundPositions.length > 0) {
        data.boundSphere = Cesium.BoundingSphere.fromPoints(boundPositions);
      }
      //线
      data.polylines = window.viewer.entities.add({
        polyline: {
          positions: boundPositions,
          // clampToGround: true,
          material: new Cesium.PolylineGlowMaterialProperty({
            color: Cesium.Color.fromCssColorString("#87F7F8"),
          }),
          width: 6,
        },
      });
      /*飞行到点位 */
      this.flyToBoundingSphere(boundPositions, {});
      return [data.labelCollection, data.polylines, data.pointCollection];
    },

    // 飞行到点位集合
    flyToBoundingSphere(boundPositions, options) {
      // console.log("flyToBoundingSphere boundPositions",boundPositions,"options",options);
      if (boundPositions.length > 0) {
        var boundSphere = Cesium.BoundingSphere.fromPoints(boundPositions);
        // if(boundPositions.length===1){
        var r = 2 * boundSphere.radius;
        // console.log(r)
        if (r > 10000) {
          r += r;
        } else {
          r += 10000;
        }
        var heading = Cesium.Math.toRadians(0.0);
        var pitch = Cesium.Math.toRadians(-90.0);
        var hpRange = new Cesium.HeadingPitchRange(heading, pitch, r);
        options.offset = hpRange;
        // console.log("flyToBoundingSphere options", options);
        window.viewer.camera.flyToBoundingSphere(boundSphere, options);
      }
    },

    // 展示真实杆塔模型
    showTowerRealModel(url, height, callBack) {
      let towerTileset = new Cesium.Cesium3DTileset({
        url: url,
      });
      console.log(url);
      if (height === null) {
        height = 0;
      }
      towerTileset.readyPromise
        .then((tileset) => {
          window.viewer.scene.primitives.add(tileset);
          let cartographic = Cesium.Cartographic.fromCartesian(
            tileset.boundingSphere.center
          );

          // offset相对与surface做一定的偏移，这里手动指定向下偏移50 ，让杆塔到地面
          let surface = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude,
            0.0
          );
          let offset = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude,
            parseFloat(height)
          ); // 1:-50
          let translation = Cesium.Cartesian3.subtract(
            offset,
            surface,
            new Cesium.Cartesian3()
          );
          tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
          let lat = Cesium.Math.toDegrees(cartographic.latitude);
          let lng = Cesium.Math.toDegrees(cartographic.longitude);
          let alt = cartographic.height;

          window.viewer.flyTo(towerTileset, {
            duration: 4,
            offset: {
              heading: Cesium.Math.toRadians(30),
              pitch: Cesium.Math.toRadians(-10),
              range: 300, // 为了兼容大小模型 暂时  小： 60
            },
          });

          callBack({
            lat: lat,
            lng: lng,
            towerTileset: towerTileset,
            height: alt,
          });
        })
        .otherwise(function (error) {
          console.log(error);
        });
    },

    loadKML(url) {
      let options = {
        camera: window.viewer.scene.camera,
        canvas: window.viewer.scene.canvas,
        clampToGround: true, // 开启贴地
      };
      window.viewer.dataSources
        .add(Cesium.KmlDataSource.load(url, options))
        .then(function (dataSource) {
          let entities = dataSource.entities.values;
          for (let i = 0; i < entities.length; i++) {
            let entity = entities[i]; // 设置每个entity的样式
            entity.polyline.show = true;
            entity.polyline.width = 3;
            entity.polyline.material =
              new Cesium.PolylineOutlineMaterialProperty({
                color: Cesium.Color.BLUE,
                outlineWidth: 3,
                outlineColor: Cesium.Color.WHITE,
              });
          }
          window.viewer.flyTo(dataSource);
        });
    },
  },
};
</script>
<style lang="scss">
.cesium {
  width: 100%;
  height: 100%;
}
#cesium_container {
  width: 100%;
  height: 100%;
  min-width: 400px;

  canvas {
    width: 100% !important;
  }
}
</style>
